package com.example.lock;

import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁：分为读锁和写锁，多个读锁不互斥，读锁与写锁互斥，写锁与写锁互斥，
 * 这是由jvm自己控制的，你只要上好相应的锁即可。如果你的代码只读数据，可以很多人同时读，
 * 但不能同时写，那就上读锁；如果你的代码修改数据，只能有一个人在写，
 * 且不能同时读取，那就上写锁。总之，读的时候上读锁，写的时候上写锁！
 * @author 夏焰波
 * @date 2020-06-02 0:00
 */
public class ReadWriteLockTest {
    public static void main(String[] args) {
        final Queue3 q3 = new Queue3();
        for (int i = 0; i < 3; i++) {
            new Thread() {
                public void run() {
                    while (true) {
                        q3.get();
                    }
                }
            }.start();
            new Thread(){
                public void run(){
                    while(true){
                        q3.put(new Random().nextInt(1000));
                    }
                }
            }.start();
        }
    }
}

class Queue3 {
    //共享数据，只能有一个线程能写该数据，但可以有多个线程同时读该数据
    private Object data = null;
    ReadWriteLock rwl = new ReentrantReadWriteLock();

    public void get() {
        rwl.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " be ready to read data!");
            Thread.sleep((long) Math.random() * 1000);
            System.out.println(Thread.currentThread().getName() + " have read data:" + data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rwl.readLock().unlock();
        }
    }

    public void put(Object data) {
        rwl.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " be ready to read data!");
            this.data = data;
            Thread.sleep((long) Math.random() * 1000);
            System.out.println(Thread.currentThread().getName() + " have read data:" + data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rwl.writeLock().unlock();
        }
    }
}
